import os
import subprocess
from subprocess import Popen, PIPE
from time import sleep

import yaml
from jsonpath import jsonpath



class Utils:
    @classmethod
    def jsonpath(cls, json_object, expr):
        """通过表达式'$...key'遍历json_object, 返回json[key]=value,返回[value]"""
        return jsonpath(json_object, expr)

    @classmethod
    def load_yaml(cls, path):
        """读取指定路径"""
        data = yaml.safe_load(open(path, encoding="utf-8"))
        # print(data)
        # if isinstance(data[0], dict):
        #     return [list(i.values()) for i in data]
        return data

    # open appium server, emulator, uiautomatorviewer, and then connect emulator
    @classmethod
    def connect(cls):
        # open appium server, emulator, uiautomatorviewer
        # cmd_list = [r"start appium", r"D:\Program Files\MuMu\emulator\nemu\EmulatorShell\NemuPlayer.exe", r"adb disconnect 127.0.0.1:7555"]
        cmd_list = [r"start appium", r"D:\LeiDian\LDPlayer4.0\dnplayer.exe", r"start uiautomatorviewer"]
        for cmd in cmd_list:
            print(cmd)
            if 'start' in cmd:
                os.system(cmd)
            else:
                Popen(cmd)

        # connect emulator
        # for i in range(20):
        #     p = Popen(r'adb connect 127.0.0.1:7555', stdout=PIPE)
        #     res = p.stdout.read().decode("utf-8")
        #     print(res)
        #     # if res == "connected to 127.0.0.1:7555" or res == "already connected to 127.0.0.1:7555":
        #     if "connected" in res:
        #         Popen(r"adb devices")
        #         break
        #     sleep(2)



if __name__ == '__main__':
    # utils = Utils()
    # utils.clear_all_calendar()
    # data = Utils.load_yaml("../data/api/calendar/event/event.yml")['create_event']
    # # ids = [d.pop() for d in data]
    # print(data[-1])
    # for i in data[-1]:
    #     if i != -1:
    #         print(len(i))
    #         print(i)
    # print(data)
    Utils.connect()
